package com.jboost.modules.app.controller;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.google.common.util.concurrent.AtomicDouble;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.jboost.common.api.vo.Result;
import com.jboost.common.util.HttpRestUtils;
import com.jboost.common.util.JSONUtil;
import com.jboost.modules.app.dto.*;
import com.jboost.modules.system.entity.LxPriceData;
import com.jboost.modules.system.mapper.LxPriceDataMapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpHeaders;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.lang.reflect.Field;
import java.util.*;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

import static com.jboost.modules.app.constant.Strategy.query_all_api;
import static com.jboost.modules.app.service.strategry.liangxin.LxLowPriceQuery.LX_OTHER_PRICE;

@Api(tags = "客户管理")
@RestController
@RequestMapping("/liangxin")
@Slf4j
@AllArgsConstructor
public class LxController {


    StringRedisTemplate redisTemplate;
    LxPriceDataMapper lxPriceDataMapper;



    @GetMapping(value = "/fyMerge")
    @ApiOperation(value = "发运合并", notes = "数据转换")
    public List<List<String>> push1(@RequestParam(name = "msg",required = false) String msg, @RequestParam(name = "tj",required = false) String tj) throws Exception {
        List<List<String>> newList = new ArrayList<>();
        List<Integer> indexs = Arrays.stream(tj.split(",")).map(e -> Integer.parseInt(e)).collect(Collectors.toList());
        String[] msgSplit = msg.split(",");
        List<List<String>> values = Arrays.stream(msgSplit).map(e -> Arrays.stream(e.split("\\｜")).collect(Collectors.toList())).collect(Collectors.toList());

        Map<String, List<List<String>>> listMap = values.stream()
                .collect(Collectors.groupingBy(s -> {
                    String key = "";
                    for (Integer index : indexs) {
                        key = key + s.get(index-1);
                    }
                    return key;
                }));
        listMap.values().forEach(e->{
            List<String> one = e.get(0);
            one.set(32,e.stream().map(e1 -> Double.parseDouble(e1.get(32))).reduce(0d, Double::sum).toString());
            one.set(9,e.stream().map(e1 -> Double.parseDouble(e1.get(9))).reduce(0d, Double::sum).toString());
            one.set(33,e.stream().map(e1 -> Double.parseDouble(e1.get(33))).reduce(0d, Double::sum).toString());
            one.set(5,e.stream().map(e1 -> Double.parseDouble(e1.get(5))).reduce(0d, Double::sum).toString());
            one.set(6,e.stream().map(e1 -> Double.parseDouble(e1.get(6))).reduce(0d, Double::sum).toString());
            one.set(7,e.stream().map(e1 -> Double.parseDouble(e1.get(7))).reduce(0d, Double::sum).toString());
            one.set(35,e.stream().map(e1 -> Double.parseDouble(e1.get(35))).reduce(0d, Double::sum).toString());
            one.set(36,e.stream().map(e1 -> Double.parseDouble(e1.get(36))).reduce(0d, Double::sum).toString());
            one.set(37,e.stream().map(e1 -> Double.parseDouble(e1.get(37))).reduce(0d, Double::sum).toString());
            newList.add(one);
        });
        return newList;
    }

    @GetMapping(value = "/autoBox")
    @ApiOperation(value = "数据转换", notes = "数据转换")
    public List<List<String>> push(@RequestParam(name = "msg",required = false) String msg, @RequestParam(name = "zl",required = false) String zl, @RequestParam(name = "hd",required = false) String hd, @RequestParam(name = "type") String type, @RequestParam(name = "ddh") String ddh) throws Exception {
        List<List<String>> newList = new ArrayList<>();
        if ("自动分箱".equals(type)) {
          String[] split = msg.split(",");
          List<List<String>> replace = Arrays.stream(split).map(e -> {
              String[] split1 = e.split("\\|");
              return Arrays.asList(split1);
          }).collect(Collectors.toList());
          AtomicInteger num = new AtomicInteger(0);
            AtomicDouble zlSum = new AtomicDouble(0);
            AtomicDouble hdSum = new AtomicDouble(0);
          replace.forEach(e -> {
              Double zlt = Double.parseDouble(e.get(e.size() - 1));
              zlSum.addAndGet(zlt);
              Double hdt = Double.parseDouble(e.get(e.size() - 2));
              hdSum.addAndGet(hdt);
              if (zlSum.get() <= Integer.parseInt(zl) && hdSum.get() <= Integer.parseInt(hd)) {
                  num.getAndIncrement();
                  CopyOnWriteArrayList<String> value = CollectionUtil.newCopyOnWriteArrayList(e.subList(1,e.size()));
                  value.set(17,num+"");
                  value.add(String.valueOf(newList.size()+1));
                  newList.add(value);
              } else {
                  zlSum.set(0);
                  hdSum.set(0);

                  if (zlt>Integer.parseInt(zl) || hdt > Integer.parseInt(hd)) {
                      Integer sl = Integer.valueOf(e.get(21));
                      int v = zlt.intValue() / Integer.parseInt(zl) + 1;
                      int h = hdt.intValue() / Integer.parseInt(hd) + 1;
                      if (h>v){
                          v = h;
                      }
                      int slpj = sl / v;
                      for (int i =0;i<v;i++){
                          num.getAndIncrement();
                          CopyOnWriteArrayList<String> value = CollectionUtil.newCopyOnWriteArrayList(e.subList(1,e.size()));
                          value.set(17,num+"");
                          value.add(String.valueOf(newList.size()+1));
                          value.set(e.size() - 2, String.valueOf(zlt/v));
                          value.set(e.size() - 3, String.valueOf(hdt/v));
                          value.set(20,slpj+"");
                          newList.add(value);
                      }
                      CopyOnWriteArrayList<String> value = CollectionUtil.newCopyOnWriteArrayList(e.subList(1,e.size()));
                      int i = sl - v * slpj;
                      if (i >0) {
                          num.getAndIncrement();
                          value.set(17, num + "");
                          value.set(20, String.valueOf(sl - v * slpj));
                          value.add(String.valueOf(newList.size() + 1));
                          value.set(e.size() - 2, String.valueOf(zlt - v * Integer.parseInt(zl)));
                          double v1 = hdt - v * Integer.parseInt(hd);
                          if (v1 < 0) {
                              v1 = Integer.parseInt(hd);
                          }
                          value.set(e.size() - 3, String.valueOf(v1));
                          newList.add(value);
                      }
                  }else {
                      num.getAndIncrement();
                      CopyOnWriteArrayList<String> value = CollectionUtil.newCopyOnWriteArrayList(e.subList(1,e.size()));
                      value.set(17,num+"");
                      value.add(String.valueOf(newList.size()+1));
                      newList.add(value);
                  }

              }
          });

      }else {
            JdyReq jdyReq = new JdyReq();
            jdyReq.setApp_id("64760f89d660d20008f28161");
            jdyReq.setEntry_id("661e2247ce3e2ea5b1b92f11");
            jdyReq.setLimit(100);
            jdyReq.setFields(Arrays.asList("_widget_1713250888057","_widget_1713250888068"));
            JdyReq.FilterBean filterBean = new JdyReq.FilterBean();
            filterBean.setRel("and");
            List<JdyReq.FilterBean.CondBean> cond = new ArrayList<>();
            JdyReq.FilterBean.CondBean a = new JdyReq.FilterBean.CondBean();
            a.setField("_widget_1713250888057");
            a.setType("text");
            a.setMethod("eq");
            a.setValue(Arrays.asList(ddh));
            cond.add(a);
            filterBean.setCond(cond);
            jdyReq.setFilter(filterBean);
            try {
                String s = jdyQueryAll(jdyReq);
                JSONArray jsonArray = (JSONArray) JSONUtil.fromJson(s, HashMap.class).get("data");
                if (jsonArray.size() > 0) {
                    for (Object o : jsonArray) {
                        LxOrderFxDto dataBean = JSONUtil.fromJson(JSONUtil.toJson(o), LxOrderFxDto.class);
                        dataBean.get_widget_1713250888068().forEach(e->{
                            Field[] declaredFields =
                                    e.getClass().getFields();
                            List<String> value = new ArrayList<>();
                            for (Field declaredField : declaredFields) {
                                try {
                                    value.add((String) declaredField.get(e));
                                } catch (Exception ex) {

                                }
                            }
                            value.add("");
                            value.add("");
                            value.add("");
                            value.add(String.valueOf(newList.size()+1));
                            newList.add(value);
                        });
                    }

                }
            } catch (IOException ex) {

            }
      }
        for (List<String> strings : newList) {
            strings.add(UUID.randomUUID().toString());
        }
        return newList;
    }

    public String jdyQueryAll(JdyReq para) throws IOException {
        Gson gson = new Gson();
        String json = gson.toJson(para);
        Map<String, Object> map = gson.fromJson(json, new TypeToken<Map<String, Object>>() {}.getType());
        String post = HttpRestUtils.post(query_all_api , map, getJdyHeaders());
        return post;
    }

    public HttpHeaders getJdyHeaders() {
        HttpHeaders jdyHeaders = new HttpHeaders();
        jdyHeaders.set("Authorization", "Bearer " + "p3tR5libgldjiPIjD6OoyvQIU3nRxJGL");
        return jdyHeaders;
    }


    @PostMapping(value = "/query")
    @ApiOperation(value = "条件查询", notes = "条件查询")
    public Result query(@RequestBody LxPriceQueryDto lxPriceQueryDto, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
        Double price = 0d;
        double v = 0d;
        String other = redisTemplate.opsForValue().get(LX_OTHER_PRICE);
        LxOtherPrice lxPriceCalDto = JSONUtil.fromJson(other, LxOtherPrice.class);
        LxPriceData lxPriceData = new LxPriceData();
        if (ObjectUtils.equals(lxPriceQueryDto.getDm(), "是")) {
            lxPriceData = lxPriceDataMapper.selectOne(Wrappers.lambdaQuery(LxPriceData.class)
                    .eq(ObjectUtils.isNotEmpty(lxPriceQueryDto.getDmLx()),LxPriceData::getDmlx,lxPriceQueryDto.getDmLx())
                    .eq(ObjectUtils.isNotEmpty(lxPriceQueryDto.getHd()),LxPriceData::getHd,lxPriceQueryDto.getHd()));
            LowPriceJdy lowPriceJdy = null;
            if (null!=lxPriceData) {
                lowPriceJdy =  JSONUtil.fromJson(lxPriceData.getContent(), LowPriceJdy.class);
            }


            List<LxPriceData> priceData = lxPriceDataMapper.selectList(Wrappers.lambdaQuery(LxPriceData.class)
                    .eq(LxPriceData::getDm, "否"));
            LxPriceData bbLxPriceData = priceData.stream().filter(e -> ObjectUtils.equals(e.getBlpz(), "白玻")).findFirst().get();
            BasePriceJdy bblowPriceJdy = JSONUtil.fromJson(bbLxPriceData.getContent(), BasePriceJdy.class);

            LxPriceData cbLxPriceData = priceData.stream().filter(e -> ObjectUtils.equals(e.getBlpz(), "超白")).findFirst().get();
            BasePriceJdy cblowPriceJdy = JSONUtil.fromJson(cbLxPriceData.getContent(), BasePriceJdy.class);


            if (ObjectUtils.equals(lxPriceQueryDto.getBlpz(), "白玻")) {
                v = (Double.valueOf(lowPriceJdy.getPrice()) + Double.valueOf(lxPriceCalDto.getLowyf()) / 400 * lxPriceQueryDto.getHd()) / Double.valueOf(bblowPriceJdy.getKcal());
                if (ObjectUtils.equals(lxPriceQueryDto.getDmLx(), "超白玻璃")) {
                    v += Double.valueOf(lxPriceCalDto.getQldm());
                }
            }
            if (ObjectUtils.equals(lxPriceQueryDto.getBlpz(), "超白")) {
                double v1 = 0d;
                if (ObjectUtils.equals(lxPriceQueryDto.getDmLx(), "超白去料")) {
                    v += ((Double.valueOf(cblowPriceJdy.getDdi())+Double.valueOf(cblowPriceJdy.getYf())+Double.valueOf(lxPriceCalDto.getCbqlyf()))/400* lxPriceQueryDto.getHd() + Double.valueOf(lxPriceCalDto.getQldm())
                            ) / Double.valueOf(cblowPriceJdy.getKcal());
                }else {
                   v1 = (Double.valueOf(cblowPriceJdy.getDdi()) - Double.valueOf(bblowPriceJdy.getDdi())) / 400 * lxPriceQueryDto.getHd();
                    v = (Double.valueOf(lowPriceJdy.getPrice()) + v1 + Double.valueOf(lxPriceCalDto.getLowyf()) / 400 * lxPriceQueryDto.getHd()) / Double.valueOf(bblowPriceJdy.getKcal());

                }
                }

                if (ObjectUtils.equals(lxPriceQueryDto.getGh(), "是")) {
                    v += lxPriceQueryDto.getHd() * Double.valueOf(lxPriceCalDto.getGh());
                    v += lxPriceQueryDto.getHd() * Double.valueOf(lxPriceCalDto.getOther()) * 4;
                }
                if (ObjectUtils.isNotEmpty(lxPriceQueryDto.getJg())) {

                    if (ObjectUtils.equals(lxPriceQueryDto.getJg(), "中空")) {
                        v += lxPriceQueryDto.getHd() * Double.valueOf(lxPriceCalDto.getZk());
                        v += lxPriceQueryDto.getHd() * Double.valueOf(lxPriceCalDto.getOther());
                    }
                    if (ObjectUtils.equals(lxPriceQueryDto.getJg(), "夹层")) {
                        v += lxPriceQueryDto.getHd() * Double.valueOf(lxPriceCalDto.getJc());
                        v += lxPriceQueryDto.getHd() * Double.valueOf(lxPriceCalDto.getOther());
                    }
                }
                price = v;

            } else {
                lxPriceData = lxPriceDataMapper.selectOne(Wrappers.lambdaQuery(LxPriceData.class).eq(LxPriceData::getBlpz, lxPriceQueryDto.getBlpz()));
                BasePriceJdy basePriceJdy = JSONUtil.fromJson(lxPriceData.getContent(), BasePriceJdy.class);
                v = ((Double.valueOf(basePriceJdy.getDdi()) + Double.valueOf(basePriceJdy.getYf()))) / 400 * lxPriceQueryDto.getHd() / Double.valueOf(basePriceJdy.getKcal());
                if (ObjectUtils.equals(lxPriceQueryDto.getGh(), "是")) {
                    v += lxPriceQueryDto.getHd() * Double.valueOf(lxPriceCalDto.getGh());
                    v += lxPriceQueryDto.getHd() * Double.valueOf(lxPriceCalDto.getOther()) * 4;
                }
                if (ObjectUtils.isNotEmpty(lxPriceQueryDto.getJg())) {

                    if (ObjectUtils.equals(lxPriceQueryDto.getJg(), "中空")) {
                        v += lxPriceQueryDto.getHd() * Double.valueOf(lxPriceCalDto.getZk());
                        v += lxPriceQueryDto.getHd() * Double.valueOf(lxPriceCalDto.getOther());
                    }
                    if (ObjectUtils.equals(lxPriceQueryDto.getJg(), "夹层")) {
                        v += lxPriceQueryDto.getHd() * Double.valueOf(lxPriceCalDto.getJc());
                        v += lxPriceQueryDto.getHd() * Double.valueOf(lxPriceCalDto.getOther());
                    }
                }
                price = v;
            }
        return Result.OK(String.format("%.2f", price));
    }
}